﻿using CPPEI.Coolzon.Common;
using CPPEI.Update.WCF;
using CPPEI.WPF.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml;


namespace CPPEI.Coolzon.Launcher.Mini
{
    /// <summary>
    /// Interaction logic for MiniWindow.xaml
    /// </summary>
    public partial class MiniWindow : Window
    {
        /// <summary>
        /// 更新线程
        /// </summary>
        private UpdatingThread _thread;

        /// <summary>
        /// 下载线程
        /// </summary>
        private DownloadThread _downloadThread;

        /// <summary>
        /// 是否重启
        /// </summary>
        private bool _isRestart;

        /// <summary>
        /// 是否已经复制文件中
        /// </summary>
        private bool IsCopying;

        /// <summary>
        /// 是否执行取消操作
        /// </summary>
        private bool _isCancel;

        /// <summary>
        /// 被升级的应用程序信息
        /// </summary>
        private Common.AppInfo _appInfo;

        private bool isDownlaoading = false;

        private bool _isDownloadFinish = false;

        private string _destPatchFileSavePath;

        private string _PatchFileSaveFolderName;

        private string _targetVersion;

        private string _patchFileSavePath;

        private DispatcherTimer _timer;

        private ProcessCount processCount;

        private int processIndex = 1;

        /// <summary>
        /// 处理倒计时的委托
        /// </summary>    
        /// <returns></returns>
        public delegate bool CountDownHandler();

        public MiniWindow()
        {
            InitializeComponent();

            string appType = App.XCurrent.StartupParams.GetValue("P");
            _appInfo = Common.CoolzonRegistryUtil.GetAppInfo(App.XCurrent.Company, App.XCurrent.Product, appType);
            if (_appInfo == null)
            {
                // 出错，未发现应用程序信息
                Common.Logger.Error("出错，未发现应用程序{0}的信息", appType);
            }
            else
            {
                // 获取最新版本信息
                VersionHelper versionHelper = new VersionHelper(CZEnvironment.Instance.ServiceConfig.IP, CZEnvironment.Instance.ServiceConfig.Port);
                CheckResult checkResult = versionHelper.CheckVersion(_appInfo.Product, _appInfo.Type, _appInfo.Version.ToString());

                _downloadThread = new DownloadThread(CZEnvironment.Instance.ServiceConfig.IP, CZEnvironment.Instance.ServiceConfig.Port);
                _downloadThread.Progress += _downloadThread_Progress;
                _downloadThread.Failure += _downloadThread_Failure;
                _downloadThread.Finished += _downloadThread_Finished;



                if (checkResult != null)
                {
                    //string patchFileSavePath;
                    if (checkResult.HasIncrementalPatch)
                    {
                        _patchFileSavePath = GetPatchFileSavePath(checkResult, "");
                        _PatchFileSaveFolderName = string.Format("Patch_{0}-{1}", _appInfo.Version.ToString(4), checkResult.LatestVersion);
                        string destPatchFileSavePath = _patchFileSavePath + _PatchFileSaveFolderName + ".zip";
                        _downloadThread.DownloadIncrementalPatch(_appInfo.Product, _appInfo.Type, _appInfo.Version.ToString(4), checkResult.LatestVersion, destPatchFileSavePath);
                        _targetVersion = checkResult.LatestVersion;
                        _destPatchFileSavePath = destPatchFileSavePath;

                    }
                    else if (checkResult.HasFullPatch)
                    {

                        _patchFileSavePath = GetPatchFileSavePath(checkResult, "Full");
                        _PatchFileSaveFolderName = string.Format("Patch_{0}-{1}", "Full", checkResult.LatestVersion);
                        string destPatchFileSavePath = _patchFileSavePath + _PatchFileSaveFolderName + ".zip";
                        _downloadThread.DownloadFullPatch(_appInfo.Product, _appInfo.Type, checkResult.LatestVersion, destPatchFileSavePath);
                        _targetVersion = checkResult.LatestVersion;
                        _destPatchFileSavePath = destPatchFileSavePath;
                    }
                    else
                    {
                        // 启动程序
                        StartupAppUtil.StartupAppNoUpdate(_appInfo);
                        // 关闭当前程序
                        Application.Current.Shutdown();
                    }

                }
            }
        }

        void _downloadThread_Finished(string fileName, long totalSize)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                // 更新显示进度
                // 更新界面
                _ctlLblMessageSub.Text = "下载更新包完毕...";
                // _ctlLauncherClose.Visibility = System.Windows.Visibility.Hidden;
                // _ctlBtnStartNow.Visibility = System.Windows.Visibility.Visible;
                _ctlBtnCancel.Visibility = System.Windows.Visibility.Hidden;

                if (!_isDownloadFinish)
                {
                    _thread = new UpdatingThread(_appInfo, _destPatchFileSavePath, _PatchFileSaveFolderName, _targetVersion);
                    _thread.Updating += _thread_Updating;
                    _thread.UpdateFailure += _thread_UpdateFailure;
                    _thread.UpdateFinish += _thread_UpdateFinish;
                    _thread.Start();
                }

            }));

        }

        void _thread_Updating(int totalStep, int curStep, string message)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                // 更新显示进度
                // 更新界面
                IsCopying = true;
                _thread.Sleep(1000);
                _ctlLblMessageSub.Text = message;
                _ctlSPBar.Width = (1 - Convert.ToDouble(curStep) / Convert.ToDouble(totalStep)) * _ctlStackPanelBar.Width;
                // _ctlCanvas.Margin = new Thickness(_ctlStackPanelBar.Width - (1 - start / totalSize) * _ctlStackPanelBar.Width - 20, 0, 0, 0);
                // RollbackFiles(_updateFileNodes);
                //_ctlLauncherClose.Visibility = System.Windows.Visibility.Hidden;
                // _ctlBtnStartNow.Visibility = System.Windows.Visibility.Visible;
                //_ctlBtnCancel.Visibility = System.Windows.Visibility.Hidden;

            }));
        }



        /// <summary>
        /// 获取更新保存的路径
        /// </summary>
        /// <returns></returns>
        private string GetPatchFileSavePath(CheckResult checkResult, string scheduleMode)
        {
            if (checkResult == null)
            {
                return "";
            }
            PathMap.CreateSubdirectory(_appInfo.Directory, "Patches");
            string destFullName = PathMap.GetDownloadFilePath(_appInfo.Directory, "Patches", string.Empty);
            PathMap.CreateSubdirectory(destFullName, _appInfo.Product);
            destFullName = PathMap.GetDownloadFilePath(destFullName, _appInfo.Product, "\\");
            PathMap.CreateSubdirectory(destFullName, _appInfo.Type);
            destFullName = PathMap.GetDownloadFilePath(destFullName, _appInfo.Type, "\\");

            string downlodFolderName = PathMap.CreateSubdirectory(destFullName, scheduleMode, _appInfo.Version.ToString(4), checkResult.LatestVersion);
            string destRootFullName = PathMap.GetDownloadFilePath(destFullName, downlodFolderName, "\\");

            return destRootFullName;
        }

        void _downloadThread_Failure(string errorMsg, long start, int length, long totalSize)
        {
            if (!_isCancel)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    // 更新显示进度
                    // 更新界面
                    _ctlLblMessageSub.Text = errorMsg;
                    _ctlSPBar.Width = (1 - start / totalSize) * _ctlStackPanelBar.Width;

                    _ctlLauncherClose.Visibility = System.Windows.Visibility.Visible;

                    _ctlBtnCancel.Visibility = System.Windows.Visibility.Hidden;

                }));
            }
        }

        void _downloadThread_Progress(string fileName, long start, int length, long totalSize, double netSpeed)
        {
            if (!_isCancel)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    // 更新显示进度
                    // 更新界面
                    isDownlaoading = true;
                    _downloadThread.Sleep(1000 / processIndex);

                    _ctlLblMessageSub.Text = "正在下载更新包...";
                   
                    _ctlSPBar.Width = (1 - Convert.ToDouble(start + length) / Convert.ToDouble(totalSize)) * _ctlStackPanelBar.Width;

                    processIndex++;
                }));
            }
        }




        /// <summary>
        /// 更新失败
        /// </summary>
        /// <param name="totalStep"></param>
        /// <param name="curStep"></param>
        /// <param name="message"></param>
        void _thread_UpdateFailure(int totalStep, int curStep, string message)
        {
            if (!_isCancel)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    // 更新显示进度
                    // 更新界面
                    _ctlLblMessageSub.Text = message;
                    _ctlSPBar.Width = (1 - curStep / totalStep) * _ctlStackPanelBar.Width;
                    //_ctlCanvas.Margin = new Thickness(_ctlStackPanelBar.Width - (1 - curStep / totalStep) * _ctlStackPanelBar.Width - 20, 0, 0, 0);
                    _ctlLauncherClose.Visibility = System.Windows.Visibility.Visible;
                    //_ctlBtnStartNow.Visibility = System.Windows.Visibility.Visible;
                    _ctlBtnCancel.Visibility = System.Windows.Visibility.Hidden;

                }));
            }
        }

        /// <summary>
        /// 更新完成
        /// </summary>
        /// <param name="totalStep"></param>
        /// <param name="curStep"></param>
        /// <param name="message"></param>
        void _thread_UpdateFinish(int totalStep, int curStep, string message, bool isHaveUpdate)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                // 更新显示进度
                // 更新界面
                _thread.Sleep(1000);
                _ctlLblMessageSub.Text = message;
                _ctlSPBar.Width = (1 - Convert.ToDouble(curStep) / Convert.ToDouble(totalStep)) * _ctlStackPanelBar.Width;

                _ctlLauncherClose.Visibility = System.Windows.Visibility.Visible;

                _ctlBtnCancel.Visibility = System.Windows.Visibility.Hidden;

                int timeVale = 10;

                _timer = new DispatcherTimer();
                _timer.Interval = new TimeSpan(0, 0, 1);//间隔1秒

                _timer.Tick += new EventHandler(timer_Tick);

                processCount = new ProcessCount(timeVale);
                CountDown += new CountDownHandler(processCount.ProcessCountDown);

                _timer.Start();

            }));
        }

        /// <summary>
        /// 处理事件
        /// </summary>
        public event CountDownHandler CountDown;
        public bool OnCountDown()
        {
            if (CountDown != null)
                return CountDown();

            return false;
        }


        private void timer_Tick(object sender, EventArgs e)
        {
            if (OnCountDown())
            {
                _ctltimeInfo.Content = string.Format("更新程序,将在{0}秒后关闭!", processCount.GetSecond());
            }
            else
            {
                _timer.Stop();
                _ctlLauncherClose_Click(_ctlLauncherClose, null);
            }
        }


        /// <summary>
        /// 关闭按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _ctlLauncherClose_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsNeedRestart != null && App.IsNeedRestart)
            {
                // 启动程序
                StartupAppUtil.StartupAppNoUpdate(_appInfo);
            }

            //关闭程序
            Application.Current.Shutdown();

        }

        /// <summary>
        /// 下载显示取消操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _ctlBtnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (!IsCopying)
            {
                _isCancel = true;

                _downloadThread.AbortThread();

                // 关闭当前程序
                Application.Current.Shutdown();
            }
            else
            {

                _ctlLblMessageSub.Text = "更新文件中，无法进行取消操作！";
            }
        }

        /// <summary>
        /// 下载失败后立即启动操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _ctlBtnStartNow_Click(object sender, RoutedEventArgs e)
        {
            // 启动程序
            StartupAppUtil.StartupAppNoUpdate(_appInfo);
            // 关闭当前程序
            Application.Current.Shutdown();
        }
    }
}
